package com.example.iread.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Parcel;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.example.iread.R;
import com.example.iread.exception.MyException;

import java.io.FileDescriptor;
import java.io.IOException;

public class AudioPlayService extends Service {


    private MediaPlayer mediaPlayer;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = intent.getStringExtra("url");
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            try {
                mediaPlayer.setDataSource(url);
                mediaPlayer.prepare();
                mediaPlayer.start();
            } catch (IOException e) {
                throw new MyException(500, e.getMessage());
            }
        }
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mediaPlayer.stop();
        mediaPlayer = null;
    }

    public class MyBinder extends Binder {

        public void play() {
            mediaPlayer.reset();
            mediaPlayer.start();
        }

        public void resume() {
            mediaPlayer.start();
        }

        public void pause() {
            mediaPlayer.pause();
        }

        public void stop() {
            mediaPlayer.stop();
        }

        public void seekTo(int ms) {
            mediaPlayer.seekTo(ms);
        }

        public int getDuration() {
            return mediaPlayer.getDuration();
        }

        public int getCurrentPosition() {
            return mediaPlayer.getCurrentPosition();
        }

        public boolean isPlaying() {
            return mediaPlayer.isPlaying();
        }
    }
}
